<?php

namespace App\Http\Controllers\api;

use App\Models\Order;
use App\Models\Renting;
use App\Models\StoreOrder;
use App\Service\CommonService;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class PayController
{
    /**
     * User: YKY
     * DateTime: 2022/11/22 14:35
     * @return array|\Symfony\Component\HttpFoundation\Response
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * 商品支付
     */
    public function payOrder()
    {
        $orderId = request()->get('order_id');

        $pay_id = request()->get('pay_id');
        $orderData = StoreOrder::where('id', $orderId)->first()->toArray();
        $price = Renting::where('id', $orderData['uid'])->first()->toArray();
        if ($price['price'] < $orderData['pay_price']) return CommonService::fail(9999, '余额不足');
        $orderMsg = [
            //订单号
            'out_trade_no' => $orderData['order_id'],
            //订单价钱
            'total_amount' => $orderData['pay_price'],
            //订单名称拼接sku
            'subject' => $orderData['order_name'],
        ];

        $alipay = Pay::alipay(config('alipay'))->web($orderMsg);

        return $alipay->send();// laravel 框架中请直接 `return $alipay`
    }

    /**
     * User: YKY
     * DateTime: 2022/11/22 9:03
     * @return array|string
     * 同步回调
     */
    public function payCallback()
    {
        try {
            $callback = Pay::alipay(config('alipay'))->verify(); // 是的，验签就这么简单！
            $arrayCallback = $callback->toArray();
            //查询订单信息
            $order = StoreOrder::where('order_id', $arrayCallback['out_trade_no'])->first();
            if (empty($order)) return CommonService::fail(9999, '订单不存在', '');
            StoreOrder::where('order_id', $arrayCallback['out_trade_no'])->update(
                [
                    'status' => 2,
                    'pay_time' => strtotime(date('Y-m-d h:i:s')),
                ]);
            echo "
    <script type='text/javascript' src='https://res.wx.qq.com/open/js/jweixin-1.3.2.js'></script>
<script>
alert('支付成功');
wx.miniProgram.navigateTo({url:'/pages/orderlist/orderlist?uid='+5})
</script>";
        } catch (\Exception $e) {
            return CommonService::fail(9999, $e->getMessage());
        }
    }

    /**
     * User: YKY
     * DateTime: 2022/11/22 18:39
     * @return \Symfony\Component\HttpFoundation\Response
     * 异步回调
     */
    public function notify()
    {
        $alipay = Pay::alipay(config('alipay'));

        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！

            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况

            Log::debug('Alipay notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
    }

    public function refundPrice()
    {
        $orderId = request()->get('oid');
        $alipay = Pay::alipay(config('alipay'));
        $orderData = StoreOrder::where('id', $orderId)->first()->toArray();
        $order = [
            'out_trade_no' => $orderData['order_id'],
            'refund_amount' => $orderData['pay_price'],
        ];
        $result = $alipay->refund($order);
        return $result;
    }
}
